package io.xuan.modules.app.controller;

import io.xuan.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;


@Slf4j
@RestController
@RequestMapping("app/upload")
public class UploadController {

    private static final String UPLOAD_DIR = "F:/A_work_project/mp4/";

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = "multipart/form-data")
    @ResponseBody
    public R uploadFile(@RequestParam("fileName") MultipartFile file, @RequestParam("carId") String carId) {
        String msg = "AIOps, Always Online! Always in!";
        //判断文件是否为空
        if (file.isEmpty()) {
            return R.error("失败了");
        }
        String fileName = file.getOriginalFilename(); // 传入的文件名
        String filePath = UPLOAD_DIR;                // 获取本地基本路径
        String path = filePath + "/" + fileName;
        System.out.println(fileName);
        System.out.println(carId);
        File dest = new File(path);
        //判断文件是否已经存在
        if (dest.exists()) {
            return R.error("失败了");
        }
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);                  // 保存文件
        } catch (IOException e) {
            return R.error("失败了");
        }

        // 解密文件
        try {
            byte[] decryptedData = decryptFile(dest);
            // 保存解密后的文件
            Files.write(dest.toPath(), decryptedData);
        } catch (IOException e) {
            return R.error("文件解密失败");
        }

        return R.ok("成功了");
    }

    // AES解密函数
    private byte[] decryptFile(File file) throws IOException {
        // TODO: 使用相同的密钥和IV进行AES解密
        // 示例中需要提供密钥和IV的Base64编码字符串
        String aesKeyBase64 = "wTBl6h2Z6pM7OjCfQTR+3Q==";
        String aesIvBase64 = "8S1d5cFzQzXnP7bW+z5djA==";

        byte[] encryptedData = Files.readAllBytes(file.toPath());

        // 解码Base64格式的密钥和IV
        byte[] aesKey = Base64.getDecoder().decode(aesKeyBase64);
        byte[] aesIv = Base64.getDecoder().decode(aesIvBase64);

        // 进行AES解密
        // TODO: 使用您选择的AES解密方法进行解密操作

        // 示例中的解密过程
        // 实际上，您应该使用安全的方式来解密文件，这里只是一个简单示例
        byte[] decryptedData = performAESDecryption(encryptedData, aesKey, aesIv);

        return decryptedData;
    }


    private byte[] performAESDecryption(byte[] encryptedData, byte[] aesKey, byte[] aesIv) {
        try {
            // 创建AES密钥对象
            SecretKey secretKey = new SecretKeySpec(aesKey, "AES");

            // 创建AES解密器
            Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
            IvParameterSpec ivSpec = new IvParameterSpec(aesIv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

            // 进行解密
            byte[] decryptedData = cipher.doFinal(encryptedData);

            return decryptedData;
        } catch (Exception e) {
            e.printStackTrace();
            return new byte[0]; // 解密失败时返回空数组，实际情况应根据需求处理异常
        }
    }

    private void generalKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // 可以是128, 192, 256位
        SecretKey secretKey = keyGen.generateKey();
        byte[] keyBytes = secretKey.getEncoded();
        String encodedKey = Base64.getEncoder().encodeToString(keyBytes);
        System.out.println("AES密钥: " + encodedKey);

        // 生成IV
        SecureRandom random = new SecureRandom();
        byte[] iv = new byte[16]; // AES的IV大小为16字节
        random.nextBytes(iv);
        String encodedIV = Base64.getEncoder().encodeToString(iv);
        System.out.println("初始化向量 (IV): " + encodedIV);
    }
}
